﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFGame.Windows
{
    /// <summary>
    /// UserControl2.xaml 的交互逻辑
    /// </summary>
    public partial class UserControl2 : UserControl
    {
        Rectangle rect;
        int speed = 3;
        double speedX = 0;
        double speedY = 0;
        Point moveTo;
        public UserControl2()
        {
            InitializeComponent();
            rect = new Rectangle() { Width = 50, Height = 50, RadiusX = 5, RadiusY = 5, Fill = new SolidColorBrush(Colors.Black) };
            c.Children.Add(rect);
            Canvas.SetLeft(rect, 0);
            Canvas.SetTop(rect, 0);
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            double rectX = Canvas.GetLeft(rect);
            double rectY = Canvas.GetTop(rect);
            Canvas.SetLeft(rect, rectX + (rectX < moveTo.X ? speedX : -speedX));
            Canvas.SetTop(rect, rectY + (rectY < moveTo.Y ? speedY : -speedY));
        }

        private void c_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point lastPoint = moveTo;
            moveTo = e.GetPosition(c);
            double side1 = Math.Abs(lastPoint.X - moveTo.X);
            double side2 = Math.Abs(lastPoint.Y - moveTo.Y);
            double side = Math.Sqrt(side1 * side1 + side2 * side2);

            speedX = speed * side1/side;
            speedY = speed * side2/side;
        }
    }
}
